package at.com.vn.chess.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import at.com.vn.chess.bean.RoomBean;
import at.com.vn.chess.entity.User;

/**
 * Servlet implementation class RoomServlet
 */
public class RoomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ArrayList<User> userList = new ArrayList<User>();
	final Logger logger;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RoomServlet() {
		super();
		logger = Logger.getLogger( getClass() );
		logger.info( "Bat dau" );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost( HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		try {

			HttpSession session = request.getSession( true );
			String destination = "";

			String roomID = request.getParameter( "RoomID" );
			String userID = request.getParameter( "UserID" );
			String backFromChess = request.getParameter( "BackFromChess" );

			if ( backFromChess != null && !backFromChess.equals( "" ) ) {
				request.removeAttribute( "RoomID" );
				destination = "/pages/roomList.jsp"; // logged-in page
			} else if ( userID != null && !userID.equals( "" ) ) {
				if ( roomID != null && !userID.equals( "" ) ) {
					// go to ChessTable
					session.setAttribute( "currentSessionUserID", userID );
					session.setAttribute( "currentSessionRoom", RoomBean
							.getRoom( Integer.parseInt( roomID ) ) );
					destination = "/pages/chessTable.jsp";

				} else {
					// log out
					User userCheck = new User();
					userCheck.setUser_id( userID );
					userCheck.setUser_password( "" );

					session.setAttribute( "inputUser", userCheck );
					destination = "/pages/login.jsp";
				}
			}

			logger.info( "Go to: " + destination );

			RequestDispatcher rd = getServletContext()
					.getRequestDispatcher( destination );
			rd.forward( request, response );
		} catch ( Throwable theException ) {
			logger.error( theException.getStackTrace() );
			System.out.println( theException );
		}
	}
}
